package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hy.corecode.idgen.WFGIdGenerator;
import io.xxx.xbutler.data.ContactMapper;
import io.xxx.xbutler.data.RobotContactMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.Contact;
import io.xxx.xbutler.domain.GenderType;
import io.xxx.xbutler.domain.RobotContact;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 【直接回调】机器人被加/主动加好友（成为好友）回调接口
 * 条件：
 * 1、当微信用户添加机器人时，机器人开启了自动通过好友请求开关，且微信用户与机器人双边都没有好友关系；
 * 2、当微信用户添加机器人时，机器人未开启自动通过好友请求开关，且双边都不是好友关系；
 * 3、当机器人主动添加好友，好友通过验证后，回将本回调给商家；以上三种条件任意一种都会触发此回调；
 * <pre>
 * {
 *     "vcMerchantNo": "202309130012311",
 *     "vcRobotWxId": "wxid_pf532u1cchz322",
 *     "vcRobotSerialNo": "D576F6A79743192645374B94D2201603",
 *     "vcSerialNo": "",
 *     "nType": 3005,
 *     "nResult": 1,
 *     "vcResult": "SUCCESS",
 *     "nTimeStamp": 1736760020259,
 *     "Data": [
 *         {
 *             "vcFriendWxId": "wxid_8whxuqcoay422",
 *             "vcFriendSerialNo": "130BA8FDED2951E58D48B25BE530844D",
 *             "nSex": 1,
 *             "vcNickName": "拉线杆",
 *             "vcBase64NickName": "5ouJ57q/5p2G",
 *             "vcHeadImgUrl": "https://wx.qlogo.cn/mmhead/ver_1/L5EfUhBYp3NkBgbwhRIXjd0MdOvbRsy8nNH2gXplwzvVpDzT8Nt8tsdGrZxNTp6OicsYFIQFRhWCehSfhhPKAUhuCbb11mwvHMRtSExvLyt0/96",
 *             "vcRemarkName": "",
 *             "vcBase64RemarkName": "",
 *             "vcCountry": "CN",
 *             "vcProvince": "Henan",
 *             "vcCity": "Zhoukou",
 *             "vcTagIds": "",
 *             "vcWxAlias": "wx17329270083",
 *             "nIsEnterpriseFriend": 0,
 *             "nSource": 0,
 *             "PassivelyeAddSerialNo": "20250113171955668695118267919"
 *         }
 *     ]
 * }
 * </pre>
 */
@Slf4j
@Component
public class _3005Handler implements CallbackHandler {

    @Resource
    private ContactMapper contactMapper;

    @Resource
    private RobotContactMapper robotContactMapper;

    @Resource
    private WFGIdGenerator idGenerator;

    @Override
    public String name() {
        return "机器人被加/主动加好友（成为好友）回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 3005;
    }

    @Override
    public void handle(Callback callback) {
        String robotId = callback.getRobotId();
        String robotSerialNo = callback.getRobotSerialNo();
        String serialNo = callback.getSerialNo();
        JSONArray data = (JSONArray) callback.getData();
        if (StringUtils.hasText(serialNo)) {
            // 操作编号（当机器人为被动加好友时，该值为空。当机器人主动加好友时，该操作编号的值等于调用主动加好友接口时回调（3002）给商家的操作编号），
            // 该编号用于判断主动加好友和成为好友形成正确的对应关系。
            return;
        }

        for (Object datum : data) {
            JSONObject friend = JSONObject.from(datum);
            String contactId = friend.getString("vcFriendWxId");
            String contactSerialNo = friend.getString("vcFriendSerialNo");

            boolean contactExists = isExists(contactId);
            if (contactExists) {
                log.info("联系人信息已存在[serialNo:{}, robotId:{}, robotSerialNo:{}, contactId:{}, contactSerialNo:{}]",
                        serialNo, robotId, robotSerialNo, contactId, contactSerialNo);
            } else {
                Contact contact = new Contact()
                        .setId(contactId)
                        .setSerialNo(contactSerialNo)
                        .setGender(GenderType.valueOf(friend.getInteger("nSex")))
                        .setName(friend.getString("vcNickName"))
                        .setBase64Name(friend.getString("vcBase64NickName"))
                        .setAvatar(friend.getString("vcHeadImgUrl"))
                        .setRemarkName(friend.getString("vcRemarkName"))
                        .setBase64RemarkName(friend.getString("vcBase64RemarkName"))
                        .setAlias(friend.getString("vcWxAlias"))
                        .setProvince(friend.getString("vcProvince"))
                        .setCity(friend.getString("vcCity"))
                        .setCounty(friend.getString("vcCountry"));
                contactMapper.insert(contact);
            }

            boolean robotContactExists = isExists(robotId, contactId);
            if (robotContactExists) {
                log.info("机器人-联系人关系已存在[robotId:{}, contactId:{}]", robotId, contactId);
            } else {
                RobotContact robotContact = new RobotContact()
                        .setId(idGenerator.next())
                        .setRobotId(robotId)
                        .setRobotSerialNo(robotSerialNo)
                        .setContactId(contactId)
                        .setContactSerialNo(contactSerialNo)
                        .setCreatedTime(LocalDateTime.now());
                robotContactMapper.insert(robotContact);
            }
        }
    }

    private boolean isExists(String contactId) {
        LambdaQueryWrapper<Contact> wrapper = new LambdaQueryWrapper<Contact>()
                .eq(Contact::getId, contactId);
        return contactMapper.exists(wrapper);
    }

    private boolean isExists(String robotId, String contactId) {
        LambdaQueryWrapper<RobotContact> wrapper = new LambdaQueryWrapper<RobotContact>()
                .eq(RobotContact::getRobotId, robotId)
                .eq(RobotContact::getContactId, contactId);
        return robotContactMapper.exists(wrapper);
    }
}
